package com.wx.service.impl;

import java.util.UUID;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wx.exception.ServiceException;
import com.wx.mapper.UserMapper;
import com.wx.pojo.User;
import com.wx.pojo.vo.UserInfo;
import com.wx.service.UserService;
import com.wx.util.MD5Utils;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
	UserMapper userMapper;

	@Override
	public UserInfo saveUser(User user) {
		if(user==null) new IllegalArgumentException("参数异常!");
		if(Strings.isEmpty(user.getUserName())||Strings.isEmpty(user.getUserPwd())||Strings.isEmpty(user.getUserTel())) 
			throw	new IllegalAccessError("信息未填写完整！");
		//2.向数据库中添加用户信息
		//2.1  创建一个盐值 (与密码一起加密)
		String salt = UUID.randomUUID().toString().substring(0, 16);
		//2.2 对密码进行加密(SimpleHash为shiro框架提供)
		String newPwd = MD5Utils.getSaltMD5(user.getUserPwd(), salt);
		//2.3 将salt,newPwd存储到user对象
		user.setSalt(salt);
		user.setUserPwd(newPwd);
		String token = MD5Utils.getSaltMD5(user.getUserName(),UUID.randomUUID().toString());
		user.setToken(token);
		//2.4 将用户信息写入到数据库
		try {
			userMapper.insert(user);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
		return new UserInfo(user.getUserName(), user.getUserTel(), 
				user.getWechatQrCode(),token, user.getAvater());
	}


	//登录功能
	@Override
	public UserInfo login(String userName, String pwd) {
		//验证参数合法性
		if(Strings.isEmpty(userName)||Strings.isEmpty(pwd)) throw new IllegalArgumentException("用户名和密码不能为空！");
		//查询数据库
		User user = userMapper.findUserByUserName(userName);
		if(user==null) throw new IllegalArgumentException("该用户不存在！");
		//判断密码是否正确
		if (MD5Utils.getSaltverifyMD5(pwd,user.getSalt(), user.getUserPwd())) {
			//更新token   UUID.nameUUIDFromBytes("test".getBytes()).toString()
			String token = 
					MD5Utils.getSaltMD5(
							userName,
							UUID.randomUUID().toString().substring(0, 16));
			user.setToken(token);
			try {
				userMapper.updateById(user);
			} catch (Throwable e) {
				e.printStackTrace();
			}
			return new UserInfo(user.getUserName(), user.getUserTel(), 
					user.getWechatQrCode(), token, user.getAvater());
		}
		throw new ServiceException("密码错误");
	}

}
